/*
 * Copyright © 2010 Siddhanathan S.
 *
 * This file is part of JTeacher.
 *
 * JTeacher is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation version 3 of the License, or
 * any later version.
 *
 * JTeacher is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JTeacher.  If not, see <http://www.gnu.org/licenses/>.
 */

package jteacher;

/**
 * Console Window to display System.out and System.err statements
 *
 * @author Siddhanathan S.
 */

import java.awt.*;
import java.io.*;
import javax.swing.*;

public class Console extends JFrame {

    PipedInputStream piOut;
    PipedInputStream piErr;

    PipedOutputStream poOut;
    PipedOutputStream poErr;

    JTextArea textArea;
    JFrame terminal;

    public Console() throws IOException {
	terminal = new JFrame("Terminal");
	textArea = new JTextArea();

	// Set up System.out
	piOut = new PipedInputStream();
	poOut = new PipedOutputStream(piOut);	

	// Set up System.err
	piErr = new PipedInputStream();
	poErr = new PipedOutputStream(piErr);

	// Add a scrolling text area
	textArea.setEditable(false);	
    }

    public void setConsole() {

	terminal.setPreferredSize(new Dimension(300, 300));
	terminal.add(new JScrollPane(textArea), BorderLayout.CENTER);
	terminal.pack();
	terminal.setVisible(true);

	/* Set default output and error Streams */
	System.setOut(new PrintStream(poOut, true));
	System.setErr(new PrintStream(poErr, true));

	/* Create reader threads */
	new ReaderThread(piOut).start();
	new ReaderThread(piErr).start();
	// new WriterThread(piIn).start();
    }

    class ReaderThread extends Thread {
	PipedInputStream pi;

	ReaderThread(PipedInputStream pi) {
	    this.pi = pi;
	}

	@Override
	public void run() {
	    final byte[] buf = new byte[1024];
	    try {
		while (true) {
		    final int len = pi.read(buf);
		    if (len == -1) {
			break;
		    }
		    SwingUtilities.invokeLater(new Runnable() {
			public void run() {
			    textArea.append(new String(buf, 0, len));

			    // Make sure the last line is always visible
			    textArea.setCaretPosition(textArea.getDocument().getLength());
			}
		    });
		}
	    } catch (IOException e) {
		System.out.println("IO Exception >> :" + e);
	    }
	}
    }
}
